package com.mindata.blockchain.socket.client;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.common.Commonvalue;
import com.mindata.blockchain.core.event.ClientRequestEvent;
import com.mindata.blockchain.core.manager.DbBlockManager;
import com.mindata.blockchain.socket.packet.BlockPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.tio.client.ClientGroupContext;
import org.tio.core.Aio;
import org.tio.core.Node;

import javax.annotation.Resource;


/**
 * 发送消息的工具类
 *
 * @author wuweifeng wrote on 2018/3/12.
 */
@Component
public class PacketSender {
    @Resource
    ClientStarter clientStarter;
    @Resource
    Commonvalue commonvalue;
    @Resource
    DbBlockManager dbBlockManager;
    @Resource
    private ClientGroupContext clientGroupContext;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void sendGroup(BlockPacket blockPacket) {
        //对外发出client请求事件 ClientRequestEvent
        ApplicationContextProvider.publishEvent(new ClientRequestEvent(blockPacket));
        //发送到一个group 实现消息发送的地方
        Aio.sendToGroup(clientGroupContext, commonvalue.getMygroupid() + "", blockPacket);
    }

    public void sendToLeaderSet(BlockPacket blockPacket) {
        ApplicationContextProvider.publishEvent(new ClientRequestEvent(blockPacket));
        int concensusindex = (dbBlockManager.getLastBlockNumber() + 1) % commonvalue.getGroupsize();
        for (int i = 0; i <commonvalue.getShardnum(); i++) {
            logger.error("共识序列: {}, shardchannelsize: {}", concensusindex, commonvalue.getLeaderfilter().get(i).size());
            Node node = commonvalue.getLeaderfilter().get(i).get(concensusindex);
            if (clientStarter.nodeChannelMap.containsKey(node)) {
                Aio.send(clientStarter.nodeChannelMap.get(node), blockPacket);
            } else {
                logger.error("node 不存在 : {}", node);
            }
        }
    }
}
